import InterceptorManager from "./intercepterManger";
function Axios(config) {
    this.defaults = config;
    this.interceptors = {
        response: new InterceptorManager(),
        request: new InterceptorManager(),
    }
}


Axios.prototype.request = function (config) {
    // 真正发送请求的函数
    const dispatchRequst = function () {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest()
            xhr.open(config.method, config.url);
            xhr.send()
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (/^2\d{2}$/.test(xhr.status)) {
                        resolve({
                            data: xhr.response,
                            status: xhr.status,
                            config: config,
                            headers: {},
                            request: xhr
                        })
                    } else {
                        reject(xhr.status);
                    }
                }
            }

            if (config.cancelToken) {
                config.cancelToken.promise.then(() => {
                    console.log('abort'); d
                    xhr.abort();
                })
            }
        })
    }
    const chain = [dispatchRequst, undefined];
    // 请求拦截器添加成功
    this.interceptors.request.handlers.forEach(item => {
        chain.unshift(item.fulfilled, item.rejected);
    })
    // 相应拦截器
    this.interceptors.response.handlers.forEach(item => {
        chain.push(item.fulfilled, item.rejected);
    })
    console.log('chain: ', chain);
    // 创建一个成功的promise激活chain链条
    let promise = Promise.resolve();
    while (chain.length) {
        promise = promise.then(chain.shift(), chain.shift())
    }
    return promise;
}
const methods = ['put', 'post', 'delete', 'get', 'patch']
methods.forEach(methodName => {
    Axios.prototype[methodName] = function () {
        // 模拟Axios结构，没有方法具体实现
    }
})

export default Axios;